/**
 * Used on the preferences page in the language combo.
 */
package com.csaba.swing.model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class Language implements Comparable<Language>
{
	private final static Language[] languages;

	static
	{
		final Locale[] all = Locale.getAvailableLocales();
		final List<Language> allLang = new ArrayList<Language>();
		for ( int i = 0; i < all.length; i++ )
		{
			final Language lang = new Language(all[i]);
			if ( !allLang.contains(lang) )
				allLang.add(lang);
		}
		Collections.sort(allLang);
		languages = allLang.toArray(new Language[allLang.size()]);
	}

	public static Language getLanguageByCode( final String code )
	{
		for ( int i = 0; i < languages.length; i++ )
		{
			if ( languages[i].getCode().equals(code) )
				return languages[i];
		}
		return null;
	}

	public static Language[] getAvailableLanguages()
	{
		return languages;
	}

	private final String code;
	private final String name;

	public Language( final Locale locale )
	{
		code = locale.getLanguage();
		name = locale.getDisplayLanguage();
	}

	@Override
	public String toString()
	{
		return name;
	}

	@Override
	public boolean equals( final Object obj )
	{
		if ( obj instanceof Language )
		{
			return ( (Language) obj ).code.equals(code);
		}
		return false;
	}

	@Override
	public int compareTo( final Language arg0 )
	{

		return code.compareTo(arg0.code);
	}

	public String getCode()
	{
		return code;
	}

	public String getName()
	{
		return name;
	}
}